import NextAuth from 'next-auth';
import { authConfig } from '@/auth.config';
import Credentials from 'next-auth/providers/credentials';
import { User } from '@/registry/types';
import GitHub from 'next-auth/providers/github';

// 模拟数据库获取用户
async function getUserFromDb(name: string, password: string): Promise<User | null> {
    const user = {
        id: '9999',
        name: 'admin',
        email: 'yonyouai@yonyou.com',
        image: '',
    };
    if (name === user.name && password === process.env.AUTH_PASSWORD) {
        return user;
    }
    return null;
}

// 添加您的适配器和会话策略
export const { handlers, auth, signIn, signOut } = NextAuth({
    session: { strategy: 'jwt' },
    ...authConfig,
    providers: [
        GitHub({
            clientId: process.env.AUTH_GITHUB_ID,
            clientSecret: process.env.AUTH_GITHUB_SECRET,
        }),
        Credentials({
            credentials: {
                name: {},
                password: {},
            },
            authorize: async (credentials) => {
                try {
                    const { name, password } = credentials;
                    const user = await getUserFromDb(name as string, password as string);
                    if (!user) {
                        throw new Error('User not found.');
                    }
                    return user;
                } catch (error) {
                    return null;
                }
            },
        }),
    ],
});
